// pages/login/login.js
const httpUtils = require('../../utils/httpUtil')
const ui = require('../../utils/ui')

Page({
  data: {
    username: '',
    password: '',
    isLoading: false,
    errorText: '',
    rememberPwd: false,
  },

  onLoad(){
    this.setData({
      username: wx.getStorageSync('username'),
      password: wx.getStorageSync('password'),
      rememberPwd: wx.getStorageSync('rememberPwd'),
    })
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onRememberPwdTap(e) {
    this.setData({
      rememberPwd: !this.data.rememberPwd
    })
  },

  async onLogin() {
    const {
      username,
      password
    } = this.data;

    if (this.data.rememberPwd) {
      wx.setStorageSync('rememberPwd', this.data.rememberPwd);
      wx.setStorageSync('username', username);
      wx.setStorageSync('password', password);
    } else {
      wx.removeStorageSync('rememberPwd');
      wx.removeStorageSync('username');
      wx.removeStorageSync('password');
    }
    

    if (!username || !password) {
      this.setData({
        errorText: '请输入用户名和密码'
      });
      return;
    }

    this.setData({
      isLoading: true,
      errorText: ''
    });

    let obj = {
      method: "POST",
      showLoading: true,
      url: "/prod-api/wxLogin",
      message: "登录中...",
      data: {
        "username": username,
        "password": password
      }
    }

    httpUtils.request(obj).then(res=>{
      if (res.data.code == 200) {
        console.log('登录成功');
        ui.hideLoading();
        getApp().globalData.token = res.data.token;
        wx.setStorageSync('token', res.data.token);
        return httpUtils.request({
          method: "GET",
          showLoading: true,
          url: "/prod-api/getWxUserInfo",
          message: "获取用户信息...",
        });
      } else {
        this.setData({
          isLoading: false,
          errorText: res.data.msg
        })
      }
    })
    .then(res=>{
      if (res.data.code == 200) {
        getApp().globalData.userInfo = res.data.user;
        wx.setStorageSync('userInfo', res.data.user);
        if (res.data.user.dept != null) {
          if (this.options && this.options.redirect) {
            wx.redirectTo({
              url: decodeURIComponent(this.options.redirect)
            });
          } else {
            wx.switchTab({
              url: '/pages/home/home'
            });
          }
        } else {
          // 弹窗选择所属组织节点
        }
      }
    })
    .catch(err=>{
      console.log('ERROR: '+err)
    });
  }
});